package com.j1903.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

public class HttpRequest {
    //设置代理，让服务器认为是浏览器发送的请求
    private static String userAgent="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36";
    //根据传递的url抓取页面内容以字符串形式返回
    public static String sendGet(String url){
        //创建Http客户端对象，也就是模拟一个浏览器
        CloseableHttpClient hc= HttpClients.createDefault();
        //创建请求配置对象,设置超时时间
        RequestConfig reqConfig=RequestConfig.custom()
                .setSocketTimeout(2000)
                .setConnectTimeout(2000).build();
        //声明请求对象,设置请求地址
        HttpGet httpGet=new HttpGet(url);
        //声明响应对象
        CloseableHttpResponse response=null;
        String html=null;
        try {
            httpGet.setHeader("User-Agent", userAgent);
            httpGet.setConfig(reqConfig);
            //发送请求，类似在浏览器上输入地址回车
            response=hc.execute(httpGet);
            //判断状态码是否是200,200表示响应成功
            if(response.getStatusLine().getStatusCode()
                    == HttpStatus.SC_OK){
                HttpEntity entity=response.getEntity();
                //把响应对象的内容转换为字符串
                html= EntityUtils.toString(entity,"UTF-8");
            }else{
                System.out.println("返回状态码不正确");
                System.out.println(EntityUtils
                        .toString(response.getEntity(),"UTF-8"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return html;
    }

    public static String saveRemoteImg(String imgPath){
        Connection conn= Jsoup.connect(imgPath);
        String newFileName=null;
        try {
            Connection.Response response=
                    conn.method(Connection.Method.GET)
                            .ignoreContentType(true)
                            .timeout(5000).execute();
            //从响应对象获取图片的文件流，输入缓冲流
            BufferedInputStream bInputStream=
                    response.bodyStream();
            //新生成的文件名
            newFileName= UUID.randomUUID().toString()
                    .replace("-","").substring(0,20)+".png";
            File file=new File("d:"+File.separator+"//Study//xiaomiimgs"+File.separator
                    +newFileName);
            byte[] bytes=new byte[1024];
            int len;
            BufferedOutputStream bOutStream=
                    new BufferedOutputStream(
                            new FileOutputStream(file));
            while ((len=bInputStream.read(bytes, 0, 1024))!=-1){
                bOutStream.write(bytes, 0, len);
            }
            bInputStream.close();
            bOutStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newFileName;
    }
}
